package com.leilbase.jwtoauth.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: sc-alibaba
 * @description: 用户实现类
 * @author: Leil
 * @create: 2019-08-22 16:15
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImp implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImp.class);

    Map<String, User> users = new HashMap<>();

    {
        User user1 = new User("leil1", "$2a$10$cgWWDRrDO0sBiLIA8y41yemD3XvImkvcItG.gSgmXn0J0yNen0WjS", getAuthorities("USER"));
        User user2 = new User("leil2", "$2a$10$cgWWDRrDO0sBiLIA8y41yemD3XvImkvcItG.gSgmXn0J0yNen0WjS", getAuthorities("USER", "ADMIN"));
        this.users.put("leil1", user1);
        this.users.put("leil2", user2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.error("here is loadUserByUsername================================");
        User u = users.get(username);
        User user = new User(u.getUsername(), u.getPassword(), u.getAuthorities());
        return user;
    }

    private List<GrantedAuthority> getAuthorities(String... roles) {
        List<GrantedAuthority> authorities = Arrays.stream(roles)
                .map(role -> new SimpleGrantedAuthority(role))
                .collect(Collectors.toList());
        return authorities;
    }


}
